package xiaolong.lian.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ucpaas.restDemo.SysConfig;
import com.ucpaas.restDemo.client.AbsRestClient;
import com.ucpaas.restDemo.client.JsonReqClient;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xiaolong.lian.dao.UserDao;
import xiaolong.lian.entity.User;
import xiaolong.lian.exception.CustomException;
import xiaolong.lian.service.UserService;
import xiaolong.lian.util.Auth;
import xiaolong.lian.util.Path;

import java.io.File;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    public String sendAuthCode(String tel) throws CustomException {
        int code = new Random().nextInt(999999);
        AbsRestClient client = new JsonReqClient();
        SysConfig config = SysConfig.getInstance();
        String result = client.sendSms(config.getProperty("sid"),config.getProperty("token"),
                config.getProperty("app_id"),config.getProperty("template_id"),
                String.valueOf(code) + "," + config.getProperty("valid_minute"),tel,"");
        if(result.equals(""))
            throw new CustomException("发送失败");
        else{
            JSONObject jsonObject = JSONObject.parseObject(result);
            if(Integer.parseInt(jsonObject.get("code").toString()) == 0){
                return String.valueOf(code);
            }else{
                throw new CustomException(jsonObject.get("msg").toString());
            }
        }
    }

    @Transactional
    public String register(String tel, String password, String codeSent, String codePost) throws CustomException {
        User user = userDao.getUserByTel(tel);
        if(user != null)
            throw new CustomException("该手机号已注册");
        if(!codePost.equals(codeSent))
            throw new CustomException("验证码错误");
        if(userDao.addUser(tel, BCrypt.hashpw(password, BCrypt.gensalt())) != 1)
            throw new CustomException("注册失败，检查输入是否正确");
        String path = Path.getAbsolutePath("/doc");
        new File(path + "/" + tel).mkdirs();
        return Auth.generateToken(tel);
    }

    public String login(String tel, String password) throws CustomException {
        User user = userDao.getUserByTel(tel);
        if(user == null)
            throw new CustomException("该手机用户不存在");
        if(!BCrypt.checkpw(password, user.getPassword()))
            throw new CustomException("密码错误");
        return Auth.generateToken(tel);
    }

    public String resetPassword(String tel, String newPassword, String codeSent, String codePost) throws CustomException {
        User user = userDao.getUserByTel(tel);
        if(user == null)
            throw new CustomException("该手机用户不存在");
        if(!codePost.equals(codeSent))
            throw new CustomException("验证码错误");
        if(userDao.updatePassword(tel, BCrypt.hashpw(newPassword, BCrypt.gensalt())) != 1)
            throw new CustomException("重置密码失败，请稍后再试");
        return Auth.generateToken(tel);
    }
}
